package monster.com.cvh.fragment;

import android.app.Activity;
import android.content.Context;
import android.support.annotation.IdRes;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import butterknife.BindView;
import butterknife.OnClick;
import monster.com.cvh.R;
import monster.com.cvh.bean.PersonalBasicBean;
import monster.com.cvh.bean.ResultBean;
import monster.com.cvh.event.RefreshCompletedEvent;
import monster.com.cvh.fragment.base.ResumeInfoBaseFragment;
import monster.com.cvh.util.CheckNetUtils;
import monster.com.cvh.util.KeyboardUtils;
import monster.com.cvh.util.MyConstant;
import monster.com.cvh.util.RegexUtils;
import monster.com.cvh.util.SPUtils;
import okhttp3.Call;
import okhttp3.Response;

/**
 * @author: 13580
 * @data: 2018/3/19
 * @function:个人信息fragment
 */

public class PersonalInfoFragment extends ResumeInfoBaseFragment implements RadioGroup.OnCheckedChangeListener {
    private static final String TAG = "PersonalInfoFragment";
    @BindView(R.id.edt_activity_personal_name)
    EditText mEdtName;
    @BindView(R.id.radio_btn_fragment_personal_info_female)
    RadioButton mRBFemale;
    @BindView(R.id.radio_btn_fragment_personal_info_male)
    RadioButton mRBMale;
    @BindView(R.id.radio_group_fragment_personal_info_sex)
    RadioGroup mRBGSex;
    @BindView(R.id.edt_fragment_personal_native_place)
    EditText mEdtNativePlace;
    @BindView(R.id.edt_fragment_personal_phone)
    EditText mEdtPhone;
    @BindView(R.id.edt_fragment_personal_email)
    EditText mEdtEmail;
    @BindView(R.id.edt_fragment_personal_qq)
    EditText mEdtQQ;
    @BindView(R.id.edt_fragment_personal_wechat)
    EditText mEdtWechat;
    @BindView(R.id.radio_btn_fragment_personal_info_unmarried)
    RadioButton mRBUnmarried;
    @BindView(R.id.radio_btn_fragment_personal_info_married)
    RadioButton mRBMarried;
    @BindView(R.id.radio_group_fragment_personal_info_marriage)
    RadioGroup mRBGMarriage;
    @BindView(R.id.edt_fragment_personal_political_state)
    EditText mEdtPoliticalState;
    @BindView(R.id.edt_fragment_personal_native)
    EditText mEdtNative;
    @BindView(R.id.tv_fragment_personal_birthday)
    TextView mTvBirthday;
    private TimePickerView mPVBirthDay;
    private PersonalBasicBean.DataBean mBean;
    private PersonalBasicBean.DataBean mCloneBean;

    public static PersonalInfoFragment newInstance() {
        PersonalInfoFragment fragment = new PersonalInfoFragment();
        return fragment;
    }


    @Override
    protected int getLayoutResId() {
        return R.layout.fragment_personal_info;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    protected void initData() {
        mDialog.show();
        OkGo.<String>get(MyConstant.GET_RESUME_BASIC)
                .tag(this)
                .params(MyConstant.TOKEN, SPUtils.getString(getContext(), MyConstant.TOKEN, ""))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            PersonalBasicBean bean = new Gson().fromJson(s, PersonalBasicBean.class);
                            if (bean != null && bean.getCode() == 1) {
                                mBean = bean.getData();
                                if (mBean.getGender().isEmpty()) {
                                    //getString 要写在 onAttach内 不然报IllegalStateException
                                    mBean.setGender("男");
                                }
                                if (mBean.getMarriage().isEmpty()) {
                                    mBean.setMarriage("未婚");
                                }
                                mCloneBean = (PersonalBasicBean.DataBean) mBean.clone();
                                Log.e(TAG, "返回的数据: '" + mBean.toString());
                                initViewData();
                            } else {
                                showToastShort(R.string.net_load_failed);
                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                            showToastShort(R.string.net_load_failed);
                        } finally {
                            mDialog.dismiss();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        mDialog.dismiss();
                        showToastShort(R.string.net_load_failed);
                    }
                });
    }

    @Override
    protected void initEvent() {

    }

    private void initViewData() {
        if (mBean != null) {
            String gender = mBean.getGender();
            String marriage = mBean.getMarriage();
            if (gender == null || gender.isEmpty()) {
                mBean.setGender(getResources().getString(R.string.fragment_person_info_personl_info_male));
            }
            if (marriage == null || gender.isEmpty()) {
                mBean.setMarriage(getString(R.string.fragment_person_info_personl_info_marriage_unmarried));
            }
            if (mBean.getGender().equals(getResources().getString(R.string.fragment_person_info_personl_info_male))) {
                mRBMale.setChecked(true);
                mRBFemale.setChecked(false);
            } else {
                mRBMale.setChecked(false);
                mRBFemale.setChecked(true);
            }

            if (!mBean.getMarriage().equals(getResources().getString(R.string.fragment_person_info_personl_info_marriage_unmarried))) {
                mRBMarried.setChecked(true);
                mRBUnmarried.setChecked(false);
            } else {
                mRBMarried.setChecked(false);
                mRBUnmarried.setChecked(true);
            }

            mEdtName.setText(mBean.getName());
            mEdtNativePlace.setText(mBean.getNative_place());
            mEdtPhone.setText(mBean.getPhone());
            mEdtEmail.setText(mBean.getEmail());
            mEdtQQ.setText(mBean.getQq());
            mEdtWechat.setText(mBean.getWechat());
            mEdtPoliticalState.setText(mBean.getParty());
            mEdtNative.setText(mBean.getRace());
            String birthday = mBean.getBirthday();
            if (mBean != null && birthday != null && birthday.length() > 0) {
                String text = birthday.substring(0, 4) + "年" + birthday.substring(5, 7) + "月" + birthday.substring(8, birthday.length()) + "日";
                mTvBirthday.setText(text);
            }
        }
        mEdtName.addTextChangedListener(new CustomerTextWatcher(mEdtName.getId()));
        mEdtNativePlace.addTextChangedListener(new CustomerTextWatcher(mEdtNativePlace.getId()));
        mEdtPhone.addTextChangedListener(new CustomerTextWatcher(mEdtPhone.getId()));
        mEdtEmail.addTextChangedListener(new CustomerTextWatcher(mEdtEmail.getId()));
        mEdtQQ.addTextChangedListener(new CustomerTextWatcher(mEdtQQ.getId()));
        mEdtWechat.addTextChangedListener(new CustomerTextWatcher(mEdtWechat.getId()));
        mEdtPoliticalState.addTextChangedListener(new CustomerTextWatcher(mEdtPoliticalState.getId()));
        mEdtNative.addTextChangedListener(new CustomerTextWatcher(mEdtNative.getId()));
        mRBGSex.setOnCheckedChangeListener(this);
        mRBGMarriage.setOnCheckedChangeListener(this);
        initPickDate();
    }

    private void initPickDate() {
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        Calendar startDate = Calendar.getInstance();
        startDate.set(1970, 0, 1);
        if (mBean != null && mBean.getBirthday() != null && mBean.getBirthday().length() > 0) {
            String birthday = mBean.getBirthday();
            selectedDate.set(Integer.parseInt(birthday.substring(0, 4)), Integer.parseInt(birthday.substring(5, 7)) - 1, Integer.parseInt(birthday.substring(8, birthday.length())));
        }
        Calendar endDate = Calendar.getInstance();
        //时间选择器 ，自定义布局
        mPVBirthDay = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                //选中事件回调,显示选中日期
                String birthday = getTime(date);
                mTvBirthday.setText(birthday);
                mTvBirthday.setTextColor(getActivity().getResources().getColor(R.color.tv_title));
                mBean.setBirthday(birthday);
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_lunar, new CustomListener() {

                    @Override
                    public void customLayout(final View v) {
                        final ImageView ivSubmit = (ImageView) v.findViewById(R.id.iv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        ivSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPVBirthDay.returnData();
                                mPVBirthDay.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mPVBirthDay.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(getResources().getColor(R.color.line_color))
                .setContentSize(20)
                .setLineSpacingMultiplier(2.0f)
                .setDecorView((ViewGroup) getActivity().getWindow().getDecorView())
                .build();
    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        return format.format(date);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }

    @OnClick({R.id.iv_include_top_bar_back, R.id.tv_include_top_bar_save, R.id.rel_activity_personal_birthday})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_include_top_bar_back:
                isSaveOnExit();
                break;
            case R.id.tv_include_top_bar_save:
                if (!CheckNetUtils.checkState_21()) {
                    InfoUnCompeledDialogFragment.getInstance(getString(R.string.net_offline)).show(getFragmentManager(), "net_offline");
                    return;
                }
                if (mCloneBean != null && mBean != null) {
                    if (!mCloneBean.equals(mBean)) {
                        saveInfoData();
                    } else {
                        KeyboardUtils.hideSoftInput((Activity) mContext);
                        ((Activity)mContext).finish();
                    }
                }
                break;
            case R.id.rel_activity_personal_birthday:
                KeyboardUtils.hideSoftInput((Activity) mContext);
                if (mPVBirthDay != null) {
                    mPVBirthDay.show();
                }
                break;
        }
    }

    private void isSaveOnExit() {
        if (!isDataChanged()) {
            mAlertDialog.show();
        } else {
            KeyboardUtils.hideSoftInput((Activity) mContext);
            ((Activity)mContext).finish();
        }
    }

    /**
     * 保存用户信息
     */
    @Override
    protected void saveInfoData() {
        if (!CheckNetUtils.checkState_21()) {
            InfoUnCompeledDialogFragment.getInstance(getString(R.string.net_offline)).show(getFragmentManager(), "net_offline");
            return;
        }
        if (mBean == null) {
            if (getActivity() != null) {
                showToastShort(R.string.net_load_failed);
                getActivity().finish();
            }
            return;
        }
        String phone = mBean.getPhone();
        String email = mBean.getEmail();
        String birthday = mBean.getBirthday();
        String temp = getString(R.string.dialog_fragment_info_un_compeled_tips);
        if (!phone.isEmpty() && !RegexUtils.isMobileExact(phone.trim())) {
            InfoUnCompeledDialogFragment.getInstance(String.format(temp, getString(R.string.fragment_person_info_personl_info_phone))).show(getFragmentManager(), "dialog_info_tips");
            return;
        }
        if (!email.isEmpty() && !RegexUtils.isEmail(email.trim())) {
            InfoUnCompeledDialogFragment.getInstance(String.format(temp, getString(R.string.fragment_person_info_personl_info_email))).show(getFragmentManager(), "dialog_info_tips");
            return;
        }
        mDialog.show();
        String text = birthday;
        if (birthday != null && !birthday.contains("年") && birthday.length() > 0) {
            text = birthday.substring(0, 4) + "年" + birthday.substring(5, 7) + "月" + birthday.substring(8, birthday.length()) + "日";
        }
        Log.e(TAG, "saveInfoDat保存的数据: " + mBean.toString());
        OkGo.<String>put(MyConstant.MODIFY_RESUME_BASIC)
                .tag(this)
                .params(MyConstant.TOKEN, SPUtils.getString(getContext(), MyConstant.TOKEN, ""))
                .params(MyConstant.BIRTHDAY, text)
                .params(MyConstant.EMAIL, email)
                .params(MyConstant.GENDER, mBean.getGender())
                .params(MyConstant.MARRIAGE, mBean.getMarriage())
                .params(MyConstant.NAME, mBean.getName())
                .params(MyConstant.NATIVE_PLACE, mBean.getNative_place())
                .params(MyConstant.PARTY, mBean.getParty())
                .params(MyConstant.PHONE, phone)
                .params(MyConstant.QQ, mBean.getQq())
                .params(MyConstant.RACE, mBean.getRace())
                .params(MyConstant.WECHAT, mBean.getWechat())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Log.e(TAG, "onSuccess: " + s);
                        try {
                            ResultBean resultBean = new Gson().fromJson(s, ResultBean.class);
                            if (resultBean.getCode() == 1) {
                                showToastShort(R.string.net_save_success);
                                //通知刷新完成度
                                RefreshCompletedEvent.getInstance().onRefreshCompleted();
                                getActivity().finish();
                            } else {
                                showToastShort(R.string.net_load_failed);
                            }
                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                            showToastShort(R.string.net_load_failed);
                        } finally {
                            mDialog.dismiss();
                            KeyboardUtils.hideSoftInput((Activity) mContext);
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        showToastShort(R.string.net_load_failed);
                        mDialog.dismiss();
                    }
                });
    }

    @Override
    public boolean isDataChanged() {
        if (mBean == null || mCloneBean == null) {
            return true;
        }
        boolean equals = mBean.equals(mCloneBean);
        return equals;
    }

    @Override
    public void onExit() {
        isSaveOnExit();
    }

    @Override
    public void onCheckedChanged(RadioGroup radioGroup, int id) {
        switch (id) {
            case R.id.radio_btn_fragment_personal_info_male:
                mBean.setGender(getString(R.string.fragment_person_info_personl_info_male));
                break;
            case R.id.radio_btn_fragment_personal_info_female:
                mBean.setGender(getString(R.string.fragment_person_info_personl_info_female));
                break;
            case R.id.radio_btn_fragment_personal_info_unmarried:
                mBean.setMarriage(getString(R.string.fragment_person_info_personl_info_marriage_unmarried));
                break;
            case R.id.radio_btn_fragment_personal_info_married:
                mBean.setMarriage(getString(R.string.fragment_person_info_personl_info_marriage_married));
                break;
        }
    }

    protected class CustomerTextWatcher implements TextWatcher {
        private int viewId;

        public CustomerTextWatcher(@IdRes int viewId) {
            this.viewId = viewId;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {
            String str = editable.toString();
            switch (viewId) {
                case R.id.edt_activity_personal_name:
                    mBean.setName(str);
                    break;
                case R.id.edt_fragment_personal_native_place:
                    mBean.setNative_place(str);
                    break;
                case R.id.edt_fragment_personal_phone:
                    mBean.setPhone(str);
                    break;
                case R.id.edt_fragment_personal_email:
                    mBean.setEmail(str);
                    break;
                case R.id.edt_fragment_personal_qq:
                    mBean.setQq(str);
                    break;
                case R.id.edt_fragment_personal_wechat:
                    mBean.setWechat(str);
                    break;
                case R.id.edt_fragment_personal_political_state:
                    mBean.setParty(str);
                    break;
                case R.id.edt_fragment_personal_native:
                    mBean.setRace(str);
                    break;
            }
        }
    }


}
